package org.bigzero.postbank

import groovy.sql.Sql
import org.junit.Test

import grails.test.*

class MetaDataDBServiceTests extends GroovyTestCase {
   def metaDataDBService
	def dataSource
	
	protected void setUp() {
		super.setUp()
		MetaData.list().each {it.delete(flush:true)}

		def db = new Sql(dataSource)
		try{
			db.execute("drop table ${metaDataDBService.META_TABLE_NAME}".toString())
		}
		catch(Exception e){
		}// 抛弃异常
	}

	protected void tearDown() {
		super.tearDown()
	}

	@Test
	void 当表已存在时创建局点数据表将成功(){
		createTableByMetaDataName("DOG")
		createTableByMetaDataName("PIG")
		MetaData.list().each {
			if (it.name.startsWith("DOG")) it.delete()
		}

		createTableByMetaDataName("CAT")
		//不存在的数据将清空
		def db = new Sql(dataSource)
		def rs = db.rows("select * from INFORMATION_SCHEMA.SYSTEM_COLUMNS where table_name = ${metaDataDBService.META_TABLE_NAME}")
		0.upto 10, {
			assertFalse rs.COLUMN_NAME.contains("DOG${it}".toString())
			assertTrue rs.COLUMN_NAME.contains("PIG${it}".toString())
		}
	}

	@Test
	void 当元数据名称为汉字时创建局点数据表应成功(){
		createTableByMetaDataName("测试")
	}

	@Test
	void 存在10个正常元数据时创建局点数据表应成功(){
		createTableByMetaDataName("TEST")
	}

	void createTableByMetaDataName(metaDataName){
		0.upto 10, {
			def metaData = new MetaData(name:"${metaDataName}${it}", dataType:"String")
			metaData.save()
		}
		def rs = createTable()
		0.upto 10, {
			assertTrue rs.COLUMN_NAME.contains("${metaDataName}${it}".toString())
			assertEquals rs.DATA_TYPE[it], 12 // 12:varchar
		}
	}

	@Test
	void 没有个元数据时应不创建局点数据表(){
		def rs = createTable()
		assertTrue rs.size() == 0
	}

	def createTable(){
		def db = new Sql(dataSource)
		metaDataDBService.resetTable()
		return db.rows("select * from INFORMATION_SCHEMA.SYSTEM_COLUMNS where table_name = ${metaDataDBService.META_TABLE_NAME}")
	}
}
